<template>
	<view class="all">
		<Header :title="t('management.workRecord')" />
		<view class="scroll">
			<scroll-view
				scroll-y
				:scroll-into-view="'list-' + selTimezone"
				class="scroll-box">
				<up-list
					class="cell-list"
					v-if="reportList.length && !isLoading">
					<up-list-item
						v-for="(item, index) in reportList"
						:key="`item-${index}`">
						<up-cell @click="goDetail(item)">
							<template #icon>
								<up-image
									width="40"
									height="21"
									mode="widthFix"
									:src="item.mapUrl" />
							</template>
							<template #title>
								<view class="tilte-box">
									<view class="left">
										<view class="left-flex">
											<view
												:class="
													item.exception === 'Normal'
														? 'tag succcess'
														: 'tag warn'
												">
												{{
													item.exception === "Normal"
														? t("job.normal")
														: t("job.anomaly")
												}}
											</view>
											<view class="time">
												{{ item.time }}
											</view>
										</view>
										<view class="left-flex">
											<view class="area">
												{{ t("report.plan.area") }}：{{
													item.area || "0.00"
												}}m²
											</view>
											<view class="area">
												{{ t("report.plan.time") }}：
												{{
													(
														item.cleaning_time / 60
													).toFixed(0) +
														t(
															"recordDetails.minute"
														) +
														(
															item.cleaning_time %
															60
														).toFixed(0) +
														t(
															"recordDetails.sec"
														) || "0.00"
												}}
											</view>
										</view>
									</view>
									<view class="right-box">
										<up-icon name="arrow-right"></up-icon>
									</view>
								</view>
							</template>
						</up-cell>
					</up-list-item>
				</up-list>
				<view class="loading" v-show="isLoading">
					<LoadingDots />
				</view>
				<view class="no-more" v-if="reportList.length && isLoadMore">
					{{ t("noMore") }}
				</view>
				<up-empty
					v-if="!reportList.length && !isLoading"
					icon="/static/image/common/noData.svg"
					width="35%"
					textSize="18"
					text-color="#b8b8b8"
					safeAreaInsetBottom
					:text="t('noList')"></up-empty>
			</scroll-view>
		</view>
	</view>
</template>

<script setup lang="ts">
import Header from "@/components/header/index.vue";
import { onReachBottom, onLoad, onPullDownRefresh } from "@dcloudio/uni-app";
import { getWorkInfoApi } from "@/service/index";
import type * as type from "../tabs/report/type";
import { useReportDetailStore } from "@/stores/index";
import { useI18n } from "vue-i18n";
import { getCurrentInstance, ref, reactive, onMounted } from "vue";
import LoadingDots from "@/components/LoadingDots/index.vue";
import moment from "moment-timezone";
const detailStore = useReportDetailStore();
const reportList = ref<FormattedWorkRecord[]>([]);
const selTimezone = ref<number>(0);
const { locale, t } = useI18n();
const instance: any = getCurrentInstance();
const isLoading = ref(false);
const isLoadMore = ref(false);
const query = reactive({
	device_sn: "",
	page: 1,
	size: 10,
	type: 0, // 0: 所有工作记录, 1: 正常工作记录, 2: 异常工作记录
});
// 定义组件内部使用的格式化记录接口
interface FormattedWorkRecord {
	record_id: string;
	mapUrl: string;
	mapYaml: string;
	exception: string;
	cleaning_time: string;
	time: string;
	start_time: string;
	start_time_pretty: string;
	end_time: string;
	end_time_pretty: string;
	average_velocity: string;
	progress: number;
	area: string;
	drawing_path: string;
	map_name: string;
}
const format = (num: number | string): string => {
	const parsed = Number(num);
	return isNaN(parsed) ? "0.00" : parsed.toFixed(2);
};
const formatTime = (seconds?: number): string => {
	if (!seconds) return "";
	const minutes = (seconds / 60).toFixed(0);
	const second = (seconds % 60).toFixed(0);
	return `${minutes}${t("recordDetails.minute")}${second}${t(
		"recordDetails.sec"
	)}`;
};
// 添加工作记录到列表
const addWorkList = (records: WorkRecord[]): void => {
	records.forEach((record: WorkRecord) => {
		const item = record.record;
		if (!item.record_id) return;
		// 查找对应的地图信息
		const mapStore: any = useUniversalStorage<string>("Map_Store", null);
		const mapInfo = mapStore.value?.map_info;
		const mapUrl = mapInfo?.map_docs[0]?.oss_url || "";
		const mapYaml = mapInfo?.map_docs[1]?.oss_url || "";

		// 格式化记录数据
		const formattedRecord: FormattedWorkRecord = {
			record_id: item.record_id,
			mapUrl,
			mapYaml,
			exception: item.exception,
			cleaning_time: item.cleaning_time || "",
			time: item.start_time_pretty
				? item.start_time_pretty.slice(0, 10).replace(/-/g, "/")
				: "",
			start_time: item.start_time,
			start_time_pretty: item.start_time_pretty
				? item.start_time_pretty
						.slice(5, 16)
						.replace(/-/g, "/")
						.replace(/T/g, " ")
				: "",
			end_time: item.end_time,
			end_time_pretty: item.end_time_pretty
				? item.end_time_pretty
						.slice(5, 16)
						.replace(/-/g, "/")
						.replace(/T/g, " ")
				: "",
			average_velocity: item.average_velocity?.toString() || "",
			progress: item.progress || item.process || 0,
			area: item.area?.toFixed(2) || "",
			drawing_path: item.drawing_path || "",
			map_name: item.map || "",
		};

		// 检查是否已存在该记录
		const isExisting = reportList.value.some(
			(it) => it.record_id === formattedRecord.record_id
		);

		if (!isExisting) {
			reportList.value.push(formattedRecord);
		}
	});
};
const getReportList = async () => {
	try {
		isLoading.value = true;
		const { data } = await getWorkInfoApi(query);

		if (data?.code === 0) {
			if (data.code === 0) {
				const workListData: WorkRecord[] =
					data.data.clean_records || [];

				if (workListData.length > 0) {
					if (query.page === 1) {
						reportList.value = [];
					}
					query.page += 1;
					addWorkList(workListData);
				} else if (query.page !== 1) {
					isLoadMore.value = true;
				}
			}
		} else {
			instance.proxy.$message(
				data?.msg || t("request.failed"),
				"warning"
			);
		}
	} finally {
		isLoading.value = false;
	}
};
const goDetail = (item: type.DeviceItem) => {
	const userTz = useUniversalStorage<string>(
		"SELECTED_TIMEZONE",
		"Asia/Shanghai"
	);
	if (userTz.value) {
		// 转换时间戳（假设为秒）
		item.start_time = item.start_time
			? moment
					.unix(item.start_time)
					.tz(userTz.value)
					.format("MM/DD HH:mm")
			: "";
		item.end_time = item.end_time
			? moment.unix(item.end_time).tz(userTz.value).format("MM/DD HH:mm")
			: "";
	} else {
		item.start_time = item.start_time_pretty;
		item.end_time = item.end_time_pretty;
	}
	detailStore.reportDetailData = item;
	detailStore.setReportDetail(item);
	uni.navigateTo({
		url: "/pages/tabs/report/detail/index?type=2",
	});
};
// 上拉加载更多
onReachBottom(async () => {
	if (isLoadMore.value || isLoading.value) return;
	try {
		await getReportList();
	} finally {
		isLoading.value = false;
	}
});
//下拉刷新
onPullDownRefresh(() => {
	setTimeout(() => {
		query.page = 1;
		reportList.value = [];
		getReportList();
		uni.stopPullDownRefresh();
	}, 1500);
});
const topHeight = ref("0");
onMounted(() => {
	// 获取状态栏高度
	// #ifdef APP-PLUS
	const statusBarHeight = ref(0);
	const systemInfo = uni.getSystemInfoSync();
	statusBarHeight.value = systemInfo.statusBarHeight || 0;
	topHeight.value = statusBarHeight.value + "px";
	// #endif
});
onLoad((options) => {
	if (options?.device_sn) {
		query.device_sn = options.device_sn;
		getReportList();
	}
});
</script>

<style lang="scss" scoped>
.all {
	background-color: #fff;
}
:deep(.u-line) {
	display: none !important;
}
:deep(.u-cell__body) {
	padding: 12px 15px !important;
}
:deep(.u-cell) {
	box-shadow: 0px 1px 4px 1px rgba(0, 0, 0, 0.12);
	border-radius: 10px;
	margin: 6px 15px 6px 15px;
	background-color: #fff;
	flex-direction: row;
	cursor: pointer;
}
.cell-list {
	box-sizing: border-box;
	display: flex;
	align-items: center;
	.tilte-box {
		display: flex;
		justify-content: space-between;
		width: 100%;
		align-items: center;
	}
	.left {
		margin-left: 10px;
		display: flex;
		flex-direction: column;
		.left-flex {
			display: flex;
			margin-bottom: 5px;
			gap: 10px;
		}
		.tag {
			font-size: 14px;
			font-weight: 600;
			padding: 2px 2px 2px 2px;
			border-radius: 4px;
		}
		.succcess {
			color: #00a870;
			background: #daf2ea;
		}
		.warn {
			color: rgb(237, 123, 47);
			background: rgb(253, 235, 223);
		}
		.time {
			padding: 3px 2px 3px 2px;
			font-size: 12px;
			color: #999;
		}
		.area {
			font-size: 12px;
			color: #999;
		}
	}
}
.loading {
	height: 100vh;
	background-color: #d8d8d8;
}
.no-more {
	width: 100%;
	height: 25px;
	line-height: 25px;
	text-align: center;
	color: #999;
	font-size: 14px;
	margin-top: 20px;
}
</style>
